import React, { useState, useRef } from "react";
import styled, { keyframes } from "styled-components";
import { FaUserEdit, FaWeixin, FaQq, FaCamera } from "react-icons/fa";
import { store } from "@/store";
import { Form, Input, Dialog, Toast, TextArea, ImageUploader } from "antd-mobile";
import type { ImageUploadItem } from 'antd-mobile/es/components/image-uploader'
import { motion } from "framer-motion";
import { useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import { PageLayout } from '@/components/grid/PageLayout';
import UploadModal from '@/components/upload/UploadModal';

const theme = {
  primary: '#6366F1',
  secondary: '#818CF8',
  background: '#F7F7F7',
  text: '#2D3436',
  lightText: '#64748B',
};

interface UserFormValues {
  nickname: string;
  bio: string;
  wechat?: string;
  qq?: string;
  currentPassword?: string;
  newPassword?: string;
  confirmPassword?: string;
}

interface SocialButtonProps {
  type: 'wechat' | 'qq';
  onClick: () => void;
  children: React.ReactNode;
  isActive?: boolean;
  theme?: string;
}

const SocialButtonComponent: React.FC<SocialButtonProps> = ({ type, onClick, children, isActive, theme }) => (
  <StyledSocialButton onClick={onClick} isActive={isActive} theme={theme}>
    {children}
  </StyledSocialButton>
);

const AvatarOptionsContainer = styled.div`
  padding: 16px;
`;

const AvatarOption = styled.div`
  padding: 12px;
  text-align: center;
  color: var(--adm-color-text);
  cursor: pointer;
  border-radius: 8px;
  
  &:hover {
    background: var(--adm-color-box);
  }
`;

const getThemeStyles = (theme: string) => {
  switch (theme) {
    case 'pink':
      return {
        gradient: 'linear-gradient(to right, #EC4899, #F472B6)',
        bgGradient: 'linear-gradient(to bottom right, rgba(236, 72, 153, 0.1), rgba(244, 114, 182, 0.05))',
        borderColor: 'rgba(236, 72, 153, 0.2)',
        hoverColor: '#EC4899',
        hoverBg: 'rgba(236, 72, 153, 0.05)',
      };
    case 'green':
      return {
        gradient: 'linear-gradient(to right, #10B981, #34D399)',
        bgGradient: 'linear-gradient(to bottom right, rgba(16, 185, 129, 0.1), rgba(52, 211, 153, 0.05))',
        borderColor: 'rgba(16, 185, 129, 0.2)',
        hoverColor: '#10B981',
        hoverBg: 'rgba(16, 185, 129, 0.05)',
      };
    case 'sky':
      return {
        gradient: 'linear-gradient(to right, #0EA5E9, #38BDF8)',
        bgGradient: 'linear-gradient(to bottom right, rgba(14, 165, 233, 0.1), rgba(56, 189, 248, 0.05))',
        borderColor: 'rgba(14, 165, 233, 0.2)',
        hoverColor: '#0EA5E9',
        hoverBg: 'rgba(14, 165, 233, 0.05)',
      };
    default:
      return {
        gradient: 'var(--adm-color-primary)',
        bgGradient: 'white',
        borderColor: 'var(--adm-color-border)',
        hoverColor: 'var(--adm-color-primary)',
        hoverBg: 'rgba(0, 0, 0, 0.05)',
      };
  }
};

const AvatarSection = styled.div<{ theme: string }>`
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 20px;
  background: ${props => getThemeStyles(props.theme).bgGradient};
  border-radius: 12px;
  border: 1px solid ${props => getThemeStyles(props.theme).borderColor};
  transition: all 0.3s ease;
`;

const AvatarWrapper = styled.div`
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
    
    .overlay {
      opacity: 1;
    }
  }
`;

const AvatarOverlay = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s ease;
  
  svg {
    color: white;
    font-size: 24px;
  }
`;

const Avatar = styled.img`
  width: 100%;
  height: 100%;
  object-fit: cover;
`;

const FormSection = styled.div<{ theme: string }>`
  background: white;
  border-radius: 12px;
  border: 1px solid var(--adm-color-border);
  overflow: hidden;
  transition: all 0.3s ease;
  
  .adm-list-item {
    &:active {
      background-color: ${props => getThemeStyles(props.theme).hoverBg};
    }
  }
`;

const FormContent = styled.div`
  display: flex;
  flex-direction: column;
  gap: 16px;
`;

const UserInfoContainer = styled.div`
  width: 100%;
`;

const StyledInput = styled(Input)`
  &.adm-input {
    border: 1px solid #E2E8F0;
    border-radius: 8px;
    padding: 8px 12px;
    
    &:focus {
      border-color: ${theme.primary};
    }
  }
`;

const StyledTextArea = styled(TextArea)`
  &.adm-text-area {
    border: 1px solid #E2E8F0;
    border-radius: 8px;
    padding: 8px 12px;
    
    &:focus {
      border-color: ${theme.primary};
    }
  }
`;

const ButtonContainer = styled.div`
  display: flex;
  gap: 10px;
  margin-top: 20px;
`;

const SocialButtonsContainer = styled.div`
  display: flex;
  gap: 10px;
  margin: 12px 0;
`;

const StyledSocialButton = styled.button<{ isActive?: boolean; theme?: string }>`
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: white;
  border: 1px solid var(--adm-color-border);
  border-radius: 8px;
  padding: 10px;
  color: var(--adm-color-text);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    border-color: ${props => getThemeStyles(props.theme || '').hoverColor};
    color: ${props => getThemeStyles(props.theme || '').hoverColor};
    background: ${props => getThemeStyles(props.theme || '').hoverBg};
  }
`;

const ActionButton = styled.button<{ variant?: 'primary' | 'secondary'; theme: string }>`
  width: 100%;
  padding: 12px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  background: ${props => getThemeStyles(props.theme).gradient};
  color: white;
  margin-top: 24px;
  transition: all 0.3s ease;
  
  &:hover {
    opacity: 0.9;
    transform: translateY(-1px);
  }
  
  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
    transform: none;
  }
`;

const UserCard: React.FC = () => {
  const [isEditing, setIsEditing] = useState(false);
  const [showPasswordModal, setShowPasswordModal] = useState(false);
  const [avatar, setAvatar] = useState<string>(store.getState().useUserReducer.avatar);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const state = store.getState();
  const [form] = Form.useForm<UserFormValues>();
  const navigate = useNavigate();
  const theme = useSelector((state: any) => state.theme);
  const { t } = useTranslation();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showAvatarOptions, setShowAvatarOptions] = useState(false);
  const [showUploadModal, setShowUploadModal] = useState(false);

  const handleAvatarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const result = e.target?.result as string;
        setAvatar(result);
        // TODO: 处理头像上传到服务器
        Toast.show({
          icon: 'success',
          content: t('头像更新成功'),
        });
      };
      reader.readAsDataURL(file);
    }
    setShowAvatarOptions(false);
  };

  const handleAvatarClick = () => {
    setShowAvatarOptions(true);
  };

  const handleEdit = async () => {
    if (isEditing) {
      try {
        const values = await form.validateFields();
        console.log('表单数据：', values);
        // TODO: 处理表单提交
        Toast.show({
          icon: 'success',
          content: '保存成功',
        });
      } catch (error) {
        Toast.show({
          icon: 'error',
          content: '请检查表单信息',
        });
        return;
      }
    }
    setIsEditing(!isEditing);
  };

  const handlePasswordChange = async () => {
    const result = await Dialog.confirm({
      content: (
        <Form layout="vertical">
          <Form.Item
            label={t('当前密码')}
            name="currentPassword"
            rules={[{ required: true, message: t('请输入当前密码') }]}
          >
            <Input type="password" placeholder={t('请输入当前密码')} />
          </Form.Item>
          <Form.Item
            label={t('新密码')}
            name="newPassword"
            rules={[{ required: true, message: t('请输入新密码') }]}
          >
            <Input type="password" placeholder={t('请输入新密码')} />
          </Form.Item>
          <Form.Item
            label={t('确认密码')}
            name="confirmPassword"
            rules={[
              { required: true, message: t('请确认新密码') },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error(t('密码不一致')));
                },
              }),
            ]}
          >
            <Input type="password" placeholder={t('请确认新密码')} />
          </Form.Item>
        </Form>
      ),
    });
  };

  const handleBindAccount = (type: 'wechat' | 'qq') => {
    Toast.show({
      icon: 'loading',
      content: type === 'wechat' ? t('正在绑定微信') : t('正在绑定QQ'),
    });
    // TODO: 实现账号绑定逻辑
  };

  const handleAvatarUpload = async (images: string[]) => {
    if (images.length > 0) {
      setAvatar(images[0]);
      // TODO: 处理头像上传到服务器
      Toast.show({
        icon: 'success',
        content: t('用户.头像.更新成功'),
      });
    }
  };

  const onFinish = async (values: UserFormValues) => {
    setIsSubmitting(true);
    try {
      // TODO: 实现保存逻辑
      Toast.show({
        icon: 'success',
        content: t('成功'),
      });
      navigate(-1);
    } catch (error) {
      Toast.show({
        icon: 'error',
        content: t('错误'),
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <PageLayout 
      title={t('用户.编辑资料')}
      onBack={() => navigate(-1)}
    >
      <Container>
        <AvatarSection theme={theme}>
          <AvatarWrapper onClick={handleAvatarClick}>
            <Avatar src={avatar} alt={t('用户.头像.替代文本')} />
            <AvatarOverlay>
              <FaCamera size={20} />
            </AvatarOverlay>
          </AvatarWrapper>
          {showAvatarOptions && (
            <AvatarOptionsContainer>
              <AvatarOption onClick={() => {
                fileInputRef.current?.click();
                setShowAvatarOptions(false);
              }}>
                {t('从相册选择')}
              </AvatarOption>
              <AvatarOption onClick={() => {
                // TODO: 实现调用相机功能
                Toast.show({
                  content: t('正在打开相机'),
                });
                setShowAvatarOptions(false);
              }}>
                {t('拍照')}
              </AvatarOption>
            </AvatarOptionsContainer>
          )}
          <input
            type="file"
            ref={fileInputRef}
            accept="image/*"
            onChange={handleAvatarChange}
            style={{ display: 'none' }}
          />
        </AvatarSection>

        <FormSection theme={theme}>
          <Form
            form={form}
            onFinish={onFinish}
            initialValues={{
              nickname: state.useUserReducer.username,
              bio: '',
            }}
            footer={
              <ActionButton 
                variant="primary"
                type="submit"
                disabled={isSubmitting}
                theme={theme}
              >
                {isSubmitting ? t('通用.加载中') : t('通用.保存')}
              </ActionButton>
            }
          >
            <FormContent>
              <Form.Item
                label={t('昵称')}
                name="nickname"
                rules={[{ required: true, message: t('请输入昵称') }]}
              >
                <StyledInput
                  placeholder={t('请输入昵称')}
                  readOnly={!isEditing}
                  clearable={isEditing}
                />
              </Form.Item>

              <Form.Item
                label={t('个性签名')}
                name="bio"
              >
                <StyledTextArea
                  placeholder={t('请输入签名')}
                  readOnly={!isEditing}
                  rows={3}
                />
              </Form.Item>

              <SocialButtonsContainer>
                <SocialButtonComponent
                  type="wechat"
                  onClick={() => handleBindAccount('wechat')}
                >
                  <FaWeixin /> {t('绑定微信')}
                </SocialButtonComponent>
                <SocialButtonComponent
                  type="qq"
                  onClick={() => handleBindAccount('qq')}
                >
                  <FaQq /> {t('绑定QQ')}
                </SocialButtonComponent>
              </SocialButtonsContainer>

              <Form.Item
                name="wechat"
                label="WeChat"
              >
                <Input placeholder={t('请输入微信号')} />
              </Form.Item>

              <Form.Item
                name="qq"
                label="QQ"
              >
                <Input placeholder={t('请输入QQ号')} />
              </Form.Item>

              <Form.Item
                name="currentPassword"
                label={t('当前密码')}
              >
                <Input
                  type="password"
                  placeholder={t('请输入当前密码')}
                />
              </Form.Item>

              <Form.Item
                name="newPassword"
                label={t('新密码')}
                rules={[
                  { 
                    validator: async (_, value) => {
                      if (value && value.length < 6) {
                        throw new Error(t('密码太短'));
                      }
                    }
                  }
                ]}
              >
                <Input
                  type="password"
                  placeholder={t('请输入新密码')}
                />
              </Form.Item>

              <Form.Item
                name="confirmPassword"
                label={t('确认密码')}
                rules={[
                  {
                    validator: async (_, value) => {
                      if (value !== form.getFieldValue('newPassword')) {
                        throw new Error(t('密码不一致'));
                      }
                    }
                  }
                ]}
              >
                <Input
                  type="password"
                  placeholder={t('请确认新密码')}
                />
              </Form.Item>
            </FormContent>
          </Form>
        </FormSection>

        <UploadModal
          visible={showUploadModal}
          onClose={() => setShowUploadModal(false)}
          onSubmit={handleAvatarUpload}
          maxCount={1}
          title={t('用户.头像.更新')}
        />
      </Container>
    </PageLayout>
  );
};

export default UserCard;

// 样式与动画
const fadeIn = keyframes`
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
`;

const Container = styled.div`
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
`;
